﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using Volo.Abp.Account.Localization;
using Volo.Abp.AspNetCore.Mvc.UI.RazorPages;
using Volo.Abp.Identity;
using IdentityUser = Volo.Abp.Identity.IdentityUser;

namespace Volo.Abp.Account.Public.Web.Pages.Account
{
    public abstract class AccountPageModel : AbpPageModel
	{
		public IAccountAppService AccountAppService { get; set; }

		public SignInManager<IdentityUser> SignInManager { get; set; }

		public IdentityUserManager UserManager { get; set; }

		protected AccountPageModel()
		{
			base.ObjectMapperContext = typeof(AbpAccountPublicWebModule);
			base.LocalizationResourceType = typeof(AccountResource);
		}

		protected RedirectResult RedirectSafely(string returnUrl, string returnUrlHash = null)
		{
			return base.Redirect(this.GetUrl(returnUrl, returnUrlHash));
		}

		private string GetUrl(string returnUrl, string returnUrlHash = null)
		{
			returnUrl = this.GetCurrentUrl(returnUrl);
			if (!AbpStringExtensions.IsNullOrWhiteSpace(returnUrlHash))
			{
				returnUrl += returnUrlHash;
			}
			return returnUrl;
		}

		private string GetCurrentUrl(string returnUrl)
		{
			if (returnUrl.IsNullOrEmpty())
			{
				return this.GetAppHomeUrl();
			}
			if (base.Url.IsLocalUrl(returnUrl))
			{
				return returnUrl;
			}
			return this.GetAppHomeUrl();
		}

		protected virtual void CheckCurrentTenant(Guid? tenantId)
		{
			if (base.CurrentTenant.Id != tenantId)
			{
				throw new ApplicationException(string.Format("Current tenant is different than given tenant. CurrentTenant.Id: {0}, given tenantId: {1}", base.CurrentTenant.Id, tenantId));
			}
		}

		protected virtual string GetAppHomeUrl()
		{
			return "~/";
		}
	}
}
